#7th Feb, 2008
#Elsewhere we've got 96 Councillors
#This on the sample may08_02_.pdf gives 91 CSVs elements of which we get 79 matches, 12 edge cases
#ruby script/runner lib\extract_councillors_from_minutes.rb

require 'rubygems'
require 'pdf/reader'

class PageTextReceiver
    attr_accessor :content

    def initialize
      @content = []
    end

    # Called when page parsing starts
    def begin_page(arg = nil)
      @content << ""
    end

    # record text that is drawn on the page
    def show_text(string, *params)
      @content.last << string.strip
    end

    # there's a few text callbacks, so make sure we process them all
    alias :super_show_text :show_text
    alias :move_to_next_line_and_show_text :show_text
    alias :set_spacing_next_line_show_text :show_text

    # this final text callback takes slightly different arguments
    def show_text_with_positioning(*params)
      params = params.first
      params.each { |str| show_text(str) if str.kind_of?(String)}
    end
end

  sample_pdf = "doc/14may08_2_.pdf" 
  receiver = PageTextReceiver.new
  pdf = PDF::Reader.file( sample_pdf, receiver )
  minutes_text = receiver.content.inspect

  start_councillors_text = "Councillors"
  end_councillors_text = "Also Present"

  present_index = minutes_text.index("Present:") 
  councillors_index = minutes_text.index(start_councillors_text) #TODO-make mode end of pattern (and take offset out)
  end_councillors_index = minutes_text.index(end_councillors_text)

  councillors_text =  minutes_text[ (councillors_index+start_councillors_text.length) ... end_councillors_index]
  councillors_csv = councillors_text.split(',')

i = 0
puts "CSV elements="+councillors_csv.size.to_s

councillors_csv.each{ |attendee_name|

 attendee_name = attendee_name.strip
 #Do we have an initial? i.e. J. Battle, and R. Battle
 attendee_name_split = attendee_name.split(' ')

 if attendee_name_split.length > 1
    puts "We have an Initial:"+attendee_name_split.first + " " + attendee_name_split.last
    db_councillor = Councillor.find(:first, :conditions => ["first_name LIKE ? AND last_name LIKE ?",attendee_name_split.first.first + "%", attendee_name_split.last])

    unless db_councillor.nil?
      puts "in db as "+db_councillor.full_name
      i = i + 1      
    else
      puts "NO MATCH"+attendee_name_split.first + " " + attendee_name_split.last
    end
 else
    puts "We have just a Surname: "+attendee_name_split.first
    db_councillor = Councillor.find(:first, :conditions => ["last_name LIKE ?", attendee_name_split.first])
    unless db_councillor.nil?
      puts "in db as "+db_councillor.full_name
      i = i+1
    else
      puts "NO MATCH "+attendee_name_split.first
  end

 end
 
}
 puts i

#TODO-clean up Adobe Formating of apostrophes
#TODO - add chair, who is in the first bit of text in the header before the councillors list

